package leetcode;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2022-02-09 23:36
 **/
public class LeetCode2166 {

    int[] bits;
    //位集大小
    int size;
    //是否反转
    boolean flipped;
    //未反转时的1的个数
    int bitCount;

    public LeetCode2166(int size) {
        this.size = size;
        bits = new int[size];
        flipped = false;
    }

    public void fix(int idx) {
        if (flipped) {
            //反转情况下,如果某一位为1,则其代表1
            if (bits[idx] == 1) {
                --bitCount;
                bits[idx] = 0;
            }
        } else {
            //未反转情况下
            if (bits[idx] == 0) {
                ++bitCount;
                bits[idx] = 1;
            }
        }
    }

    public void unfix(int idx) {
        if (flipped) {
            if (bits[idx] == 0) {
                ++bitCount;
                bits[idx] = 1;
            }
        } else {
            if (bits[idx] == 1) {
                --bitCount;
                bits[idx] = 0;
            }
        }
    }

    public void flip() {
        flipped = !flipped;
    }

    public boolean all() {
        return flipped && bitCount == 0 || !flipped && bitCount == size;
    }

    public boolean one() {
        return flipped && bitCount < size || !flipped && bitCount > 0;
    }

    public int count() {
        return flipped?size-bitCount:bitCount;
    }

    public String toString() {
        StringBuilder builder = new StringBuilder();
        if (flipped) {
            for (int bit : bits) {
                builder.append(bit == 1 ? 0 : 1);
            }
        } else {
            for (int bit : bits) {
                builder.append(bit);
            }
        }

        return builder.toString();
    }

}
